package com.xlizen;

import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.ModbusException;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.io.ModbusTransport;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;

public class ModbusBleConnection {

    private ModbusTransport modbusTransport;

    public ModbusBleConnection() {
        prepareTransport();
    }

    public ModbusTransport getModbusTransport() {
        return modbusTransport;
    }


    private void prepareTransport() {
        modbusTransport = new ModbusBleTransport();
    }


    public static void main(String[] args) throws ModbusException {
        final ModbusBleConnection modbusBleConnection = new ModbusBleConnection();
        new Thread(() -> {
            ModbusBleTransaction modbusBleTransaction = new ModbusBleTransaction(modbusBleConnection);
            ReadCoilsRequest request = new ReadCoilsRequest(1, 1);
            request.setUnitID(1);
            modbusBleTransaction.setRequest(request);
            try {
                modbusBleTransaction.execute();
                ReadCoilsResponse response = (ReadCoilsResponse) modbusBleTransaction.getResponse();
                System.out.println(response.getCoilStatus(0));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            ModbusBleTransport modbusTransport = (ModbusBleTransport) modbusBleConnection.getModbusTransport();
            modbusTransport.onWrite(true);
            modbusTransport.onReceive(new byte[]{58, 48, 49, 48, 49, 48, 49, 48, 49, 70, 67, 13, 10});
            try {
                ReadCoilsResponse modbusResponse = (ReadCoilsResponse) modbusTransport.readResponse();
                System.out.println(modbusResponse.getCoilStatus(0));
            } catch (ModbusIOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
